import { Button, Space, Collapse, Form, Input, DatePicker,Table,Pagination,Tag, message} from 'antd';
import React, { useState,useEffect } from 'react';
import { useNavigate } from 'react-router-dom'
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import {getSelectTime} from '../../../utils/publicFun'
import { getRefundAll ,getByCondition} from '../../../api/OrderApi'
import './css/OrderRefund.css'
const { Panel } = Collapse;

// import myContext from '../../../utils/myContext'

interface DataType {
	key: React.Key;
	marketState:number;//申请状态
	orderId:number;
	marketTime:string;//申请时间
	marketNum: number;//申请编号
	orderTotal: number;
	handlingTime: string; //处理时间
	salesType:number;//售后类型
  }

  
export default function RefundList() {

	const [form] = Form.useForm();
	// const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [data,setData]=useState<DataType[]>([])  //所有退款申请数据
	const [isSelect, SetIsSelect] = useState('all')  //选中按钮
	const [pageCount,setPageCount]=useState<number>()  //订单条数
	const [pageSize,setPageSize]=useState<number>(2) //每页条数
	const [currentPage,setCurrentPage]=useState<number>(1) //当前第几页
	const navigate=useNavigate()  //路由跳转对象
	const [selectState,setSelectState]=useState<number>(4) //当前在哪个状态下

	const [AfterCount1,setAfterCount1]=useState<number>(); 
	const [AfterCount2,setAfterCount2]=useState<number>(); 
	const [AfterCount3,setAfterCount3]=useState<number>(); 
	const [allAfterCount,setAllAfterCount]=useState<number>(); 

	const columns: ColumnsType<DataType> = [
		{
		  title: '序号',
		  dataIndex: 'orderId',
		  render: (_, record) => (
			<Space size="middle">
			  <Button type="link">GS{record.orderId}</Button>
			</Space >
		  ),
		},
		{
		  title: '订单编号',
		  dataIndex: 'orderId',
		},
		{
		  title: '申请时间',
		  dataIndex: 'marketTime',
		},
		{
		  title: '用户账号',
		  dataIndex: 'marketNum',
		},
		{
		  title: '退款金额',
		  dataIndex: 'orderTotal',
		  render: (_, record) => (
			  <Space size="middle">
				<Button type="link">{record.orderTotal}</Button>
			  </Space >
			),
		},
		{
			title: '类型',
			dataIndex: 'salesType',
			render: (_, record) => (
				<Space size="middle">
				{
					record.salesType==1 ? <Tag color="#EF7C15">退款</Tag> : record.salesType==2 ?<Tag color="#2CC359">退货</Tag> :  <Tag color="#F9713E">退款</Tag>
				}
				  {/* <Tag color="#EF7C15">{record.salesType==1  ? "退款" : record.salesType==2 ? '退货' : "换货"}</Tag> */}
				</Space >
			  ),
		  },
		{
		  title: '申请状态',
		  dataIndex: 'marketState',
		  render: (_, record) => (
			record.marketState == 1 ? <Tag color="#f50">待处理</Tag> : record.marketState == 2 ? <Tag color="#2db7f5">已处理</Tag> : <Tag color="#5F6368">已拒绝</Tag>
			// </Tag>
		),
		},
		{
		  title: '处理时间',
		  dataIndex: 'handlingTime',
		},
		{
			title: '操作',
			dataIndex: 'operation',
			render: (_, record) => (
			  <Space size="middle">
				<Button className='check add' onClick={()=>gotoRefundDetail(record)}>查看详情</Button>
			  </Space >
			),
		  },
	  ];

//   const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
//     console.log('selectedRowKeys changed: ', newSelectedRowKeys);
//     setSelectedRowKeys(newSelectedRowKeys);
//   };

    // 初始获取所有订单数据
	useEffect(()=>{
    //   setData(all)
	  getAll()
	},[])


	
	//页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
	const pageChange=(page:number, pageSize:number)=>{
		console.log('page pageSize',page,pageSize);
		// 发请求
		setPageSize(pageSize)
		setCurrentPage(page)
       if(selectState==4){
			getRefundAll({
				// state:selectState,
				salesType:selectState,//(查询退款),
				pageNum:page,
				size:pageSize,
			}).then(res=>{
				setData(res.data.aftermarketDtos)
				setPageCount(res.data.count)
				// 设置当前页和每页条数
				setPageSize(pageSize)
				setCurrentPage(page)
				console.log('res111',res);
				
			}).catch(err=>{
				console.log('err222',err);
				
			})
	   }else{
			getByCondition({
				marketState:selectState,
				size:pageSize,
				salesType:selectState,
				page:currentPage
			}).then(res=>{
				console.log('res',res);
				// message.success(res.msg);
				setPageCount(res.data.count)	
				setData(res.data.aftermarketDtos)
			}).catch(err=>{
				console.log('err',err);
			})
	   }


		
	}

	// 获取所有数据的函数
	const getAll=()=>{
		getRefundAll({
			salesType:selectState,//(查询所有),
			pageNum:currentPage,
			size:pageSize
		}).then(res=>{
			console.log('所有退款res',res);
			setData(res.data.aftermarketDtos)	
			setPageCount(res.data.count)	

			const {AfterCount1,AfterCount2,AfterCount3,allAfterCount } =res.data.afterCountMap
			// const {allAfterCount } =res.data.afterCountMap
			// console.log('AfterCount2',AfterCount2);
			
			setAfterCount1(AfterCount1)
			setAfterCount2(AfterCount2)
			setAfterCount3(AfterCount3)
			setAllAfterCount(allAfterCount)
		}).catch(err=>{
			console.log('err565665',err);
			
		})
	}


	// 点击头部按钮选择显示所有订单、代付款、待发货、已发货、已完成、已关闭。。。
	const clickBtns=(type:string,num:number)=>{
		console.log('type',type);
		console.log('num',num);
		// 判断点击的是哪个按钮

		setSelectState(num)
		SetIsSelect(type)
		// getOrderByState({
		// 	state:state,
		// 	pageNum:currentPage,
		// 	size:pageSize,
		// }).then(res=>{
		// 	setData(res.data.allOrderDtos)
		// 	SetIsSelect(type)
		// 	console.log('点击导航按钮查询',res.data.count);
			
		// 	setPageCount(res.data.count)
		// }).catch(err=>{
		// 	console.log('err222',err);
			
		// })
		if(selectState==4){
			getRefundAll({
				salesType:selectState,//(查询所有),
				pageNum:currentPage,
				size:pageSize
			}).then(res=>{
				console.log('所有退款res',res);
				setData(res.data.aftermarketDtos)	
				setPageCount(res.data.count)	
	
				const {AfterCount1,AfterCount2,AfterCount3,allAfterCount } =res.data.afterCountMap
				// const {allAfterCount } =res.data.afterCountMap
				// console.log('AfterCount2',AfterCount2);
				
				setAfterCount1(AfterCount1)
				setAfterCount2(AfterCount2)
				setAfterCount3(AfterCount3)
				setAllAfterCount(allAfterCount)
			}).catch(err=>{
				console.log('err565665',err);			
			})
		}else if(selectState==1){
			getByCondition({
				marketState:selectState,
				size:pageSize,
				salesType:3,
				page:currentPage
			}).then(res=>{
				console.log('res',res);
				// message.success(res.msg);
				setPageCount(res.data.count)	
				setData(res.data.aftermarketDtos)

				//
				// setAfterCount1(res.data.count)
			}).catch(err=>{
				console.log('err',err);	
			})
		}else{
			getByCondition({
				marketState:num,
				size:pageSize,
				salesType:num,
				page:currentPage
			}).then(res=>{
				console.log('res',res);
				// message.success(res.msg);
				setPageCount(res.data.count)	
				setData(res.data.aftermarketDtos)

				//
				// setAfterCount1(res.data.count)
			}).catch(err=>{
				console.log('err',err);	
			})
		}
	}

	// 点击搜索
	const onFinish = (values: any) => {
		console.log('Finish:', values);
		console.log('getSelectTime(values.submit_time)',getSelectTime(values.apply_time));	
		getByCondition({
			marketState:selectState,
			size:pageSize,
			salesType:1,
			page:currentPage,
			orderId:Number(values.keyword),
			marketTime:values.apply_time ? getSelectTime(values.apply_time) : values.apply_time
		}).then(res=>{
			console.log('res',res);
			message.success(res.msg);
			setPageCount(res.data.count)	
			setData(res.data.aftermarketDtos)
		}).catch(err=>{
			console.log('err',err);	
		})
	};

	// 搜索重置
	const resetHandle=(event:any)=>{
		// 阻止默认事件
		event.preventDefault()
		console.log('重置');	
		// 清空搜索框
		form.setFieldsValue({
            keyword:'',
			addressee:'',
			apply_time:''
        })	
		// 重新获取数据
		getAll()
	}
 
	// 点击查看退款详情
	const gotoRefundDetail = (record: DataType) => {
		// const recordArr=[]
		// recordArr.push(record)
		// 跳转到对应退款详情页
		navigate('/home/order/refundDetails', { state: record.orderId })
	}

	

	// 表格多选配置
	// const rowSelection: TableRowSelection<DataType> = {
	// 	selectedRowKeys,
	// 	onChange: onSelectChange,
	// 	selections: [
	// 	  Table.SELECTION_ALL,
	// 	  Table.SELECTION_INVERT,
	// 	  Table.SELECTION_NONE,
	// 	  {
	// 		key: 'odd',
	// 		text: 'Select Odd Row',
	// 		onSelect: (changableRowKeys) => {
	// 		  let newSelectedRowKeys = [];
	// 		  newSelectedRowKeys = changableRowKeys.filter((_, index) => {
	// 			if (index % 2 !== 0) {
	// 			  return false;
	// 			}
	// 			return true;
	// 		  });
	// 		  setSelectedRowKeys(newSelectedRowKeys);
	// 		},
	// 	  },
	// 	  {
	// 		key: 'even',
	// 		text: 'Select Even Row',
	// 		onSelect: (changableRowKeys) => {
	// 		  let newSelectedRowKeys = [];
	// 		  newSelectedRowKeys = changableRowKeys.filter((_, index) => {
	// 			if (index % 2 !== 0) {
	// 			  return true;
	// 			}
	// 			return false;
	// 		  });
	// 		  setSelectedRowKeys(newSelectedRowKeys);
	// 		},
	// 	  },
	// 	],
	//   };
	
	return (
		<div className='orderlist'>
			{/* <myContext.Provider value={{getAll}}>

			</myContext.Provider> */}
			<p className='head'>退款/货/换货申请</p>
			{/* 顶部按钮 */}
			<Space wrap className='btns'>
				<Button className={isSelect =='all' ? 'selectBtn' :''} onClick={()=>clickBtns('all',4)}>全部申请({allAfterCount})</Button>
				<Button className={isSelect =='waitdeal' ? 'selectBtn' :''} onClick={()=>clickBtns('waitdeal',1)}>待处理({AfterCount2})</Button>
				<Button className={isSelect =='dealfinish' ? 'selectBtn' :''} onClick={()=>clickBtns('dealfinish',2)}>已处理({AfterCount3})</Button>
				<Button className={isSelect =='refuse' ? 'selectBtn' :''} onClick={()=>clickBtns('refuse',3)}>已拒绝({AfterCount1})</Button>
			</Space>
			{/* 筛选查询 收起 */}
			<div className='search_box'>
				<Collapse defaultActiveKey={['1']}>
					<Panel header="筛选查询" key="1">
						{/* 搜索表单 */}
						<Form form={form} name="horizontal_login" layout="inline" onFinish={onFinish}>
							<Form.Item
								label="关键词"
								name="keyword"
								// rules={[{ required: true, message: '请输入搜索关键词' }]}
							>
								<Input placeholder="订单号/商品货号" />
							</Form.Item>
							<Form.Item
								label="收货人"
								name="addressee"
								// rules={[{ required: true, message: '请输入收货人信息' }]}
							>
								<Input
									placeholder="用户昵称/手机号"
								/>
							</Form.Item>
							<Form.Item
								label="申请时间"
								name="apply_time"
								// rules={[{ required: true, message: '请输入退款申请时间' }]}
							>
								<DatePicker showTime placeholder="请选择时间" size='small' />
							</Form.Item>
							<Form.Item shouldUpdate>
								{() => (
									<Space wrap>
										<Button
											type="primary"
											htmlType="submit"
										>
											查询
										</Button>
										<Button htmlType="button" className='orderlist_reset' onClick={resetHandle}>
											重置
										</Button>
									</Space>

								)}
							</Form.Item>
						</Form>
					</Panel>
				</Collapse>
			</div>
			{/* 表格内容 rowSelection={rowSelection}*/}
			<Table className='order_table'  columns={columns} dataSource={data}  rowKey={item=>item.orderId}
			 pagination={{
				position:['bottomCenter'],
				total:pageCount,
				defaultPageSize:pageSize,
				defaultCurrent:currentPage,
				pageSizeOptions:[2,3,5],
				showSizeChanger:true,
				showQuickJumper:true,
				onChange:pageChange,
				showTotal:(total:number) => `共有 ${total} 条数据`
			  }}
			/>
			{/* 页码 */}
			{/* <Pagination
			    onChange={pageChange}
			    className='pagination'
				total={85}
				showSizeChanger
				showQuickJumper
				showTotal={(total) => `共有 ${total} 页`}
			/> */}
		</div>
	)
}